package com.wooophone.webapp.admin.web.filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.context.request.SessionScope;


public class ValidationCodeFilter implements Filter {

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
	//	System.out.println("===================="+req.getRequestURL());
		String verifycode = req.getParameter("verifycode");

		if (verifycode == null || verifycode.trim().equals("")) {
			res.sendRedirect("admin/login.jsp");
			req.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", new BadCredentialsException("验证码错误！"));
			return;
		}

		String rand = (String) req.getSession().getAttribute("rand");
		req.getSession().removeAttribute("rand");
		if (!verifycode.equalsIgnoreCase(rand)) {
			res.sendRedirect("admin/login.jsp");
			req.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", new BadCredentialsException("验证码错误！"));
			return;
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {

	}

}
